/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.cn.xiaonuo.tcrfinance.sysmgmt.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.core.consts.CommonConstant;
import com.cn.xiaonuo.core.context.constant.ConstantContextHolder;
import com.cn.xiaonuo.core.pojo.login.SysLoginUser;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysLoginHpcInfo;
import com.cn.xiaonuo.tcrfinance.sysmgmt.entity.SysUserTokenHpcEntity;
import com.cn.xiaonuo.tcrfinance.sysmgmt.mapper.SysUserTokenHpcMapper;
import com.cn.xiaonuo.tcrfinance.sysmgmt.service.ShiroHpcService;
import com.cn.xiaonuo.tcrfinance.sysmgmt.service.SysUserTokenHpcService;
import com.cn.xiaonuo.sys.core.cache.UserCache;
import com.cn.xiaonuo.sys.core.enums.LogSuccessStatusEnum;
import com.cn.xiaonuo.sys.core.jwt.JwtPayLoad;
import com.cn.xiaonuo.sys.core.jwt.JwtTokenUtil;
import com.cn.xiaonuo.sys.core.log.LogManager;
import com.cn.xiaonuo.sys.modular.auth.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;


@Service
public class SysUserTokenHpcServiceImpl extends ServiceImpl<SysUserTokenHpcMapper, SysUserTokenHpcEntity> implements SysUserTokenHpcService {
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;
	@Resource
	private UserCache userCache;
	@Autowired
	private ShiroHpcService shiroService;
	@Autowired
	private AuthService authService;

	@Override
	public SysLoginHpcInfo createToken(SysLoginUser slLoginUser) {
		long userId=slLoginUser.getId();
		//生成一个token
		JwtPayLoad payLoad =dologin(slLoginUser);//获取公用token
		String token = JwtTokenUtil.generateToken(payLoad);
		String redisLoginUserKey = payLoad.getUuid();
		/**
		 * //当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		SysUserTokenHpcEntity tokenEntity = this.getById(userId);
		if(tokenEntity == null){
			tokenEntity = new SysUserTokenHpcEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			this.save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}*/
		SysLoginHpcInfo sysLoginInfo=new SysLoginHpcInfo();
		String tempToken= CommonConstant.TOKEN_TYPE_BEARER+" "+token;//带着token头返回
		sysLoginInfo.setToken(tempToken);
		sysLoginInfo.setExpire(EXPIRE);
		sysLoginInfo.setUserId(userId);
		sysLoginInfo.setUuid(redisLoginUserKey);
		//R r = R.ok().put("token", token).put("expire", EXPIRE).put("userId",userId);

		//return r;
		return sysLoginInfo;
	}

	@Override
	public void logout(String uuid) {
		authService.logout();
		//获取登陆用户
		//SysLoginUser loginUser=(SysLoginUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		//生成一个token
		//userCache.remove(uuid);
		//修改token
		/*SysUserTokenHpcEntity tokenEntity = new SysUserTokenHpcEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		this.updateById(tokenEntity);*/
	}
	public JwtPayLoad dologin(SysLoginUser slLoginUser){
		slLoginUser.setAdminType(1);
		JwtPayLoad payLoad = new JwtPayLoad(slLoginUser.getId().longValue(), slLoginUser.getUsername());
		//String token = JwtTokenUtil.generateToken(payLoad);
		String redisLoginUserKey = payLoad.getUuid();
		userCache.put(redisLoginUserKey, slLoginUser, Long.valueOf(60 * 60 * 24 * 30));

		//更新用户登录信息
		//slUserMapper.updateById(slUser);
		LogManager.me().executeLoginLog(slLoginUser.getUsername(), LogSuccessStatusEnum.SUCCESS.getCode(), null);
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
				new UsernamePasswordAuthenticationToken(
						slLoginUser,
						null,
						slLoginUser.getAuthorities());
		SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
		//如果开启限制单用户登陆，则踢掉原来的用户
		Boolean enableSingleLogin = ConstantContextHolder.getEnableSingleLogin();
		if (enableSingleLogin) {

			//获取所有的登陆用户
			Map<String, SysLoginUser> allLoginUsers = userCache.getAllKeyValues();
			for (Map.Entry<String, SysLoginUser> loginedUserEntry : allLoginUsers.entrySet()) {

				String loginedUserKey = loginedUserEntry.getKey();
				SysLoginUser loginedUser = loginedUserEntry.getValue();

				//如果账号名称相同，并且redis缓存key和刚刚生成的用户的uuid不一样，则清除以前登录的
				if (loginedUser.getUsername().equals(slLoginUser.getUsername())
						&& !loginedUserKey.equals(payLoad.getUuid())) {
					//获取缓存的用户
					Object cacheObject = userCache.get(loginedUserKey);

					//如果缓存的用户存在，清除会话，否则表示该会话信息已失效，不执行任何操作
					if (ObjectUtil.isNotEmpty(cacheObject)) {
						//清除登录会话
						userCache.remove(loginedUserKey);
						//创建退出登录日志
						LogManager.me().executeExitLog(slLoginUser.getUsername());
					}
				}
			}
		}
		return payLoad;
	}
}
